<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="选择产品" prop="spuId">
        <SpuShowcase v-model="formData.spuId" :limit="1" @change="handleSpuChange" />
      </el-form-item>
      <el-form-item v-if="formData.spuId" label="选择规格" prop="skuId">
        <div
          class="h-60px w-60px cursor-pointer"
          @click="handleSelectSku"
          :title="skuData.name || skuData.propertiesValue"
        >
          <div v-if="skuData && skuData.picUrl" class="select-box">
            <el-image :src="skuData.picUrl" />
          </div>
          <div v-else class="select-box" title="选择规格">
            <Icon icon="ep:plus" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" class="!w-240px" />
      </el-form-item>
      <el-form-item v-if="formData.skuId" label="图片" prop="picUrl">
        <UploadImg v-model="formData.picUrl" height="80px" />
      </el-form-item>
      <el-form-item label="成本" prop="price">
        <el-input
          v-model="computedPrice"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入成本价格，0表示免费"
          class="!w-240px"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number
          v-model="formData.stock"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="0"
          placeholder="请输入库存"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="赠品单位" prop="unit">
        <el-input
          v-model="formData.unit"
          placeholder="请输入赠品单位，如：件、条、瓶"
          maxlength="8"
          class="!w-240px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
  <SkuTableSelect ref="skuTableSelectRef" :spu-id="formData.spuId" @change="handleSkuChange" />
</template>
<script setup lang="ts" name="Linkage21ProductForm">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as Linkage21ProductApi from '@/api/promotion/linkage21/Linkage21ProductApi'
import * as ProductSpuApi from '@/api/mall/product/spu'
import ShopShowcase from '@/views/mall/shop/info/components/ShopShowcase.vue'
import SpuShowcase from '@/views/mall/product/spu/components/SpuShowcase.vue'
import SkuTableSelect from '@/views/mall/product/spu/components/SkuTableSelect.vue'
import { fenToYuan, yuanToFen } from '@/utils'

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  spuId: undefined,
  skuId: undefined,
  name: undefined,
  picUrl: undefined,
  price: 0,
  stock: 99999,
  unit: '件',
  father_percent: 0,
  grandpa_percent: 0,
  foster_percent: 0
})
const formRules = reactive({
  spuId: [{ required: true, message: '请选择产品', trigger: 'blur' }],
  skuId: [{ required: true, message: '请选择产品规格', trigger: 'blur' }]
})
const formRef = ref()

const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await Linkage21ProductApi.getDetailById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await Linkage21ProductApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await Linkage21ProductApi.updateById(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined
  }
  formRef.value?.resetFields()
}

const handleSpuChange = (spu: ProductSpuApi.Spu) => {
  formData.value.spuId = spu.id
  formData.value.name = spu.name
  formData.value.picUrl = spu.picUrl
}

const skuData = ref<any>({})
const skuTableSelectRef = ref()
const handleSelectSku = () => {
  skuTableSelectRef.value.open()
}
const handleSkuChange = (sku: ProductSpuApi.Sku) => {
  skuData.value = sku
  formData.value.skuId = sku.id
  formData.value.stock = sku.stock
  if (sku.name && sku.name.length && sku.name != '默认') {
    formData.value.name += ' ' + sku.name
  }
  if (sku.picUrl && sku.picUrl.length) {
    formData.value.picUrl = sku.picUrl
  }
}

const computedPrice = computed({
  get: () => Number(fenToYuan(formData.value.price)),
  set: (newValue: number) => {
    formData.value.price = yuanToFen(newValue)
  }
})
</script>
